#!/bin/bash
# Wrapper around luet geniso to accept a yaml as an input
set -e
SPEC=$1

if [ ! -f "${SPEC}" ] ; then
  echo "Invalid spec ${SPEC}. File not found"
  exit 1
fi

create_iso_metadata_file () {
  local iso=$1
  local sha256=$2
  local f=$3

  local d=$(date +%Y%m%d)

  echo "
date: $d
iso: $iso
sha256: ${sha256}
" > $f

  return 0
}

create_iso_metadata_jsonfile () {
  local iso=$1
  local sha256=$2
  local f=$3

  local d=$(date +%Y%m%d)

  echo "{
"date": "$d",
"iso": "$iso",
"sha256": "${sha256}"
}" > $f

  return 0
}

export OVERLAY="$(yq r $SPEC 'overlay')"
export IMAGE_NAME="$(yq r $SPEC 'image_prefix')"
date="$(yq r $SPEC 'image_date')"

if [[ "$date" == "true" ]]; then
    export IMAGE_NAME=$IMAGE_NAME$(date +%Y%m%d).iso         
else 
    export IMAGE_NAME=$IMAGE_NAME.iso
fi

# Optionally supply the name of kernel/rootfs (rootfs in cpio.xz format) located in the /boot folder
# of the overlayfs, or the initramfs one
export INITRAMFS_KERNEL="$(yq r $SPEC 'initramfs.kernel_file')"
export INITRAMFS_ROOTFS="$(yq r $SPEC 'initramfs.rootfs_file')"

export KEEP_LUET_DB="$(yq r $SPEC 'packages.keep_luet_db')"
export ISOLABEL="$(yq r $SPEC 'label')"

export LUET_PACKAGES="$(yq r -j $SPEC 'packages.rootfs' | jq -r '.[]' | xargs echo)"
export LUET_REPOS="$(yq r -j $SPEC 'repository.packages' | jq -r '.[]' | xargs echo)"
export FIRST_STAGE="$(yq r -j $SPEC 'packages.initramfs' | jq -r '.[]' | xargs echo)"
export LUET_INITRAMFS_REPOS="$(yq r -j $SPEC 'repository.initramfs' | jq -r '.[]' | xargs echo)"

export ISOIMAGE_PACKAGES="$(yq r -j $SPEC 'packages.isoimage' | jq -r '.[]' | xargs echo)"
export UEFI_PACKAGES="$(yq r -j $SPEC 'packages.uefi' | jq -r '.[]' | xargs echo)"
export OVERLAY_HOOKS="$(yq r -j $SPEC 'overlay_hooks' | jq -r '.[]' | xargs echo)"
export LUET_BIN="${LUET_BIN:-/usr/bin/luet}"
export ROOT_DIR="${ROOT_DIR:-$PWD}"
export LUET_CONFIG="$ROOT_DIR/$(yq r $SPEC 'luet.config')"
export LUET_NOLOCK="true"

echo "Packages"
echo "--------"
echo "Rootfs: $LUET_PACKAGES"
echo "UEFI: $UEFI_PACKAGES"
echo "ISO: $ISOIMAGE_PACKAGES"
echo "Initramfs: $FIRST_STAGE"
echo "Package Repositories: ${LUET_REPOS}"
echo "Initramfs Repositories: ${LUET_INITRAMFS_REPOS}"
echo "--------"
echo
echo "Overlay: $OVERLAY"
echo "Overlay Hooks: ${OVERLAY_HOOKS}"
echo "Luet: $LUET_BIN"
echo "Luet config: $LUET_CONFIG"
echo "Image name: $IMAGE_NAME"

luet geniso

IMAGE_SHA256=`sha256sum $IMAGE_NAME`

create_iso_metadata_file "$IMAGE_NAME" "$IMAGE_SHA256" "iso-meta.yaml"
create_iso_metadata_jsonfile "$IMAGE_NAME" "$IMAGE_SHA256" "iso-meta.json"

echo $IMAGE_SHA256 > $IMAGE_NAME.sha256
